package com.webinsky.web.resource;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ZeroCopyHttpOutputMessage;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import reactor.core.publisher.Mono;

@Controller
public class StaticDownloadResource {
	
	private static final Logger logger = LoggerFactory.getLogger(StaticDownloadResource.class);
	@Value("${publish.path}")
	private String BASE_PATH = "";
	/**
	 * 下载指定版本zip
	 * @param response
	 * @param request
	 * @param lang
	 * @param bookmode
	 * @param name
	 * @return
	 */
	@GetMapping("/resource/static/{lang}/{bookmode}/{versionName}/download")
	public Mono<Void> downloadRes(ServerHttpResponse response, 
				ServerHttpRequest request,
				@PathVariable("lang") String lang,
				@PathVariable("bookmode") String bookmode,
				@PathVariable("versionName") String name){

		String filename = name + ".zip";
		File file = new File(BASE_PATH + "/archives", filename);
		if (!file.exists()) {
			return null;
		}

		ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
		zeroCopyResponse.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
		zeroCopyResponse.getHeaders().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
		return zeroCopyResponse.writeWith(file, 0, file.length());
	}
}



















